package code

import (
	"context"
	"fmt"

	containertype "github.com/docker/docker/api/types/container"
)

// 停止所有正在运行的容器
func ContainerStop() {
	cli := InitClient()

	ctx := context.Background()
	containers, err := cli.ContainerList(ctx, containertype.ListOptions{})
	if err != nil {
		panic(err)
	}

	for _, container := range containers {
		fmt.Println("Stopping container: ", container.ID[:10])
		noWaitTimeout := 0 // to not wait for the container to exit gracefully
		fmt.Printf("container.State: %#v\n", container)
		if container.State == "running" {
			err := cli.ContainerStop(ctx, container.ID, containertype.StopOptions{Timeout: &noWaitTimeout})
			if err != nil {
				panic(err)
			}
			fmt.Println("停止容器:", container.ID)
		}
	}
}
